//
//  ANSelectGoodsStandardsController.m
//  WeiYiMei
//
//  Created by iMac on 2019/4/17.
//  Copyright © 2019年 liyefu. All rights reserved.
//

#import "ANSelectGoodsStandardsController.h"
#import "ANGradientButton.h"
#import "GoodsStandardsEntity.h"
#import "GoodsStandardsSectionView.h"
#import "GoodsStandardsCell.h"
#import "GoodsNumSelectView.h"

@interface ANSelectGoodsStandardsController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) UILabel *goodsNumLab;
@property (nonatomic, strong) GoodsNumSelectView *numSelectView;
@property (nonatomic, strong) ANGradientButton *sureButton;

@property (nonatomic) int goodsNum;

@end

@implementation ANSelectGoodsStandardsController

- (void)dealloc
{
    NSLog(@"%@销毁了",NSStringFromClass([self class]));
}

- (CGFloat)controllerHeight
{
    return kScreenH;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor clearColor];
    
    [self setupSubViews];
    
    self.goodsNum = 1;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = touches.allObjects.firstObject;
    CGPoint point = [touch locationInView:self.view];
    BOOL res = CGRectContainsPoint(self.contentView.frame, point);
    if (!res) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)sureAction:(id)sender
{
    NSString *params = @"";
    NSString *paramsName = @"";
    if (self.dataSource.count) {
        NSMutableString *mstring = @"".mutableCopy;
        NSMutableString *mNameString = @"".mutableCopy;
        for (GoodsStandardsSectionEntity *section in self.dataSource) {
            for (GoodsStandardsEntity *entity in section.params) {
                if (entity.selected.boolValue) {
                    [mstring appendString:entity.goodsParamId];
                    [mstring appendString:@","];
                    [mNameString appendString:entity.paramName];
                    [mNameString appendString:@","];
                }
            }
        }
        params = [mstring substringToIndex:mstring.length-1];
        paramsName = [mNameString substringToIndex:mNameString.length-1];
    }
    if (self.sureHandler) {
        self.sureHandler(params, paramsName, self.goodsNum);
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.dataSource.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSource[section].params.count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    GoodsStandardsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GoodsStandardsCell" forIndexPath:indexPath];
    GoodsStandardsEntity *entity = self.dataSource[indexPath.section].params[indexPath.item];
    cell.titleLab.text = entity.paramName;
    cell.selected = entity.selected.boolValue;
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        GoodsStandardsSectionView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"GoodsStandardsSectionView" forIndexPath:indexPath];
        header.titleLab.text = self.dataSource[indexPath.section].categoryName;
        return header;
    }
    return nil;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self selected:indexPath];
}

- (void)selected:(NSIndexPath *)indexPath
{
    GoodsStandardsSectionEntity *section = self.dataSource[indexPath.section];
    for (int i = 0; i < section.params.count; i++) {
        GoodsStandardsEntity *entity = section.params[i];
        if (i == indexPath.item) {
            entity.selected = @(YES);
        }
        else {
            entity.selected = @(NO);
        }
    }
    [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section]];
}

- (void)setDataSource:(NSArray<GoodsStandardsSectionEntity *> *)dataSource
{
    _dataSource = dataSource;
}

- (void)setupSubViews
{
    self.contentView = [[UIView alloc] init];
    self.contentView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.contentView];
    
    self.layout = [[UICollectionViewFlowLayout alloc] init];
    self.layout.headerReferenceSize = CGSizeMake(kScreenW, 40);
    self.layout.itemSize = CGSizeMake((kScreenW-60)/3, 34);
    self.layout.minimumInteritemSpacing = 15;
    self.layout.minimumLineSpacing = 15;
    self.layout.sectionInset = UIEdgeInsetsMake(0, 15, 0, 15);
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.layout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView registerClass:[GoodsStandardsCell class] forCellWithReuseIdentifier:@"GoodsStandardsCell"];
    [self.collectionView registerClass:[GoodsStandardsSectionView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"GoodsStandardsSectionView"];
    [self.contentView addSubview:self.collectionView];
    self.collectionView.allowsMultipleSelection = YES;
    
    self.goodsNumLab = [[UILabel alloc] init];
    self.goodsNumLab.font = [UIFont systemFontOfSize:14];
    self.goodsNumLab.textColor = kColor333333;
    self.goodsNumLab.text = @"数量";
    [self.contentView addSubview:self.goodsNumLab];
    
    self.numSelectView = [[GoodsNumSelectView alloc] init];
    [self.contentView addSubview:self.numSelectView];
    self.numSelectView.layer.borderColor = kColorDDD.CGColor;
    self.numSelectView.layer.borderWidth = 1;
    self.numSelectView.layer.cornerRadius = 3;
    self.numSelectView.layer.masksToBounds = YES;
    WeakSelf
    self.numSelectView.addOrDeleteHandler = ^(int num) {
        weakSelf.goodsNum = num;
    };
    
    self.sureButton = [[ANGradientButton alloc] initWithFrame:CGRectMake(0, 0, kScreenW-30, 48)];
    [self.sureButton setTitle:@"确认" forState:UIControlStateNormal];
    [self.sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.contentView addSubview:self.sureButton];
    self.sureButton.layer.cornerRadius = 24;
    self.sureButton.layer.masksToBounds = YES;
    [self.sureButton addTarget:self action:@selector(sureAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.view);
    }];
    
    [self.sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.contentView).offset(-(kiPhoneXInsetBottom+20));
        make.left.equalTo(self.contentView).offset(15);
        make.right.equalTo(self.contentView).offset(-15);
        make.height.equalTo(@48);
    }];
    
    [self.goodsNumLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.sureButton.mas_top).offset(-48);
        make.left.equalTo(self.contentView).offset(15);
    }];
    
    [self.numSelectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.contentView).offset(-15);
        make.centerY.equalTo(self.goodsNumLab);
        make.width.equalTo(@106);
        make.height.equalTo(@28);
    }];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.contentView);
        make.bottom.equalTo(self.goodsNumLab.mas_top).offset(-30);
    }];
    
    [self.collectionView layoutIfNeeded];
    CGFloat h = self.collectionView.collectionViewLayout.collectionViewContentSize.height;
    h = MIN(h, 246);
    [self.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(h));
    }];
    
}


@end
